<template>
  <!-- 添加角色表单对话框 -->
  <el-form :model="psd" label-width="120px" class="search-div">
    <el-form-item label="密码">
      <el-input show-password v-model="psd.password" />
    </el-form-item>
    <el-form-item label="新密码">
      <el-input show-password v-model="psd.newPassword" />
    </el-form-item>
    <el-form-item label="确认密码">
      <el-input show-password v-model="psd.verifyPassword" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="onEmpty">清空</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { ref } from 'vue'
import {useAccount} from '@/pinia/modules/account.js'
import { putUpdatePassword } from '@/api/user'
import router from '@/router'
//引入md5加密
import cryptoJs from 'crypto-js';
import md5 from 'crypto-js/md5';
//获取token
import { useApp } from '@/pinia/modules/app'
const appStore = useApp()
//获取pinia里的userinfo
const userinfo = ref({ ...useAccount().userinfo })
//==============================修改密码=======================================
// eslint-disable-next-line no-undef
const psd = ref({
  token: '', //token
  username: '', //用户名
  password: '', //旧密码
  newPassword: '', //新密码
  verifyPassword: '', //确认密码
})
//===========提交按钮事件======
const submit = async() => {
  //传递token给后端
  psd.value.token = appStore.authorization.token
  //进行赋值,后端根据用户名作为条件修改对应的用户
  psd.value.username = userinfo.value.userName

  // 校验两次输入的密码是否一致
  if (psd.value.verifyPassword != psd.value.newPassword) {
    ElMessage.error('两次输入的密码不一致!')
  }
  //在进行旧密码的加密校验,因为后端传来的密码是md5加密过的
  let md5Password = cryptoJs.MD5(psd.value.password).toString(cryptoJs.enc.Hex)
  if (userinfo.value.password != md5Password) {
    ElMessage.error('密码不正确!')
  }
  console.log(psd.value)
  //调用接口
  const { code } = await putUpdatePassword(psd.value)
  if (code === 200) {
    ElMessage.success('修改密码成功!')
    //更新pinia里面的数据
    //加密新密码
    let md5NewPassword = cryptoJs
      .MD5(psd.value.newPassword)
      .toString(cryptoJs.enc.Hex)
    //存入pinia
    userinfo.value.password = md5NewPassword
    //路由跳转登入界面
    router.push('/login')
  }
}
//=================清空按钮事件================
const onEmpty = () => {
  psd.value = {}
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
